package org.softmed.rest.server.defaults.boot;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.softmed.filehandling.FileUtil;
import org.softmed.rest.server.core.boot.BootupProcessor;
import org.softmed.rest.server.core.restlet.RESTServer;

import com.google.inject.Inject;
import com.google.inject.name.Named;

public class DefaultBootupProcessor implements BootupProcessor {

	@Inject
	RESTServer server;

	@Inject
	@Named("rootDir")
	String rootDir;

	@Inject
	@Named("bootDir")
	String bootDir;

	@Inject
	BootupScriptReaderUtil util;

	public void bootup() throws Throwable {
		runBootupScripts(null);
	}

	public void runBootupScripts(Map<String, Object> options) throws Throwable {
		List<File> scripts = getBootupScripts();
		util.runBootupScripts(scripts, options, server);
	}

	protected List<File> getBootupScripts() throws Throwable {

		List<File> scripts = new ArrayList<File>();

		FileUtil util = new FileUtil();
		File bootFileDir = util.getFile(bootDir);

		// File bootFileDir = null;

		// if (childs != null)
		// for (File child : childs) {
		// if (child.isDirectory() && child.getName().equals(bootDir))
		// bootFileDir = child;
		// }

		if (bootFileDir.exists() && bootFileDir.isDirectory()) {
			File[] scriptCandidates = bootFileDir.listFiles();
			if (scriptCandidates == null) {
				System.err.println("No Bottup Scripts found in directory "
						+ bootFileDir.getName() + ". Full Path: "
						+ bootFileDir.getCanonicalPath());
				return null;
			}

			for (File candidate : scriptCandidates) {
				if (candidate.isFile()
						&& candidate.getName().endsWith(".groovy"))
					scripts.add(candidate);
			}
		} else
			throw new RuntimeException("No bootup directory found!!!");

		orderScripts(scripts);

		return scripts;

	}

	private void orderScripts(List<File> scripts) {
		File[] fileArray = null;
		fileArray = scripts.toArray(new File[scripts.size()]);

		Arrays.sort(fileArray, new FileComparator());
		scripts.clear();
		scripts.addAll(Arrays.asList(fileArray));

	}

}
